package com.report.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.alibaba.fastjson.TypeReference;
import com.report.dto.*;
import com.report.entity.*;
import com.report.enumeration.MergeNodeEnum;
import com.report.enumeration.MergeTypeEnum;
import com.report.repository.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReportService {


    @Autowired
    private ReportRepository reportRepository;

    @Autowired
    private ReportMergeRecordRepository recordRepository;

    @Autowired
    private CompanyTreeStructureService companyTreeStructureService;

    @Autowired
    private TableConfigRepository tableConfigRepository;

    @Autowired
    private ReportTemplateRepository reportTemplateRepository;


    @Autowired
    private TableRowMappingRepository tableRowMappingRepository;

    public Response upsertReport(Report report) {
        Response response = new Response();

        try {
            // 1. 获取报表信息JSON字符串
            String reportInfoJson = report.getReportinfo();

            if (reportInfoJson != null && !reportInfoJson.trim().isEmpty()) {
                // 2. 解析JSON
                JSONObject jsonObject = JSON.parseObject(reportInfoJson);

                // 3. 处理displayData和data中的千分位符号
                processThousandsSeparator(jsonObject, "displayData");
                processThousandsSeparator(jsonObject, "data");

                // 4. 将处理后的JSON设置回report对象
                report.setReportinfo(jsonObject.toJSONString());
            }

            // 5. 保存处理后的报表
            response.setData(reportRepository.upsert(report));
            response.setStatus("success");
            response.setMessage("success");
        } catch (Exception e) {
            response.setStatus("error");
            response.setMessage("处理报表数据时发生错误: " + e.getMessage());
            // 记录日志
        }

        return response;
    }

    /**
     * 处理JSON对象中指定字段的千分位符号
     *
     * @param jsonObject JSON对象
     * @param fieldName  字段名（应为二维数组）
     */
    private void processThousandsSeparator(JSONObject jsonObject, String fieldName) {
        // 获取字段值
        Object fieldValue = jsonObject.get(fieldName);

        if (fieldValue instanceof List) {
            List<List<Object>> dataArray = (List<List<Object>>) fieldValue;

            // 遍历所有行和列
            for (List<Object> row : dataArray) {
                for (int i = 0; i < row.size(); i++) {
                    Object cellValue = row.get(i);

                    // 只处理字符串类型的单元格
                    if (cellValue instanceof String) {
                        String strValue = (String) cellValue;

                        // 更精确的数字格式匹配（可选）
                        if (strValue.matches("^-?\\d{1,3}(,\\d{3})*(\\.\\d+)?$")) {
                            String cleanedValue = strValue.replace(",", "");
                            row.set(i, cleanedValue);
                        }
                    }
                }
            }

            // 更新JSON对象中的字段
            jsonObject.put(fieldName, dataArray);
        }
    }

    public Response mergeReportRecords(ReportMergeRecordRequest request) {
        List<ReportMergeRecord> records = recordRepository.findBySjxmbh(request.getSjxmbh());
        Response response = new Response();
        response.setStatus("success");
        response.setMessage("success");
        response.setData(records);
        return response;
    }

    /**
     * 在公司树结构中查找指定currentCompany的节点
     *
     * @param companyList   公司树结构列表
     * @param targetCompany 目标公司标识
     * @return 找到的节点，如果未找到则返回null
     */
    private List<CompanyTreeStructureDto> findCompanyByCurrentCompany(List<CompanyTreeStructureDto> companyList, String targetCompany) {
        if (companyList == null || companyList.isEmpty()) {
            return null;
        }

        for (CompanyTreeStructureDto company : companyList) {
            // 如果当前节点匹配目标公司
            if (targetCompany.equals(company.getCurrentCompanyUscc())) {
                List<CompanyTreeStructureDto> list = new ArrayList<>();
                list.add(company);
                return list;
            }

            // 递归查找子节点
            if (company.getChildren() != null && !company.getChildren().isEmpty()) {
                List<CompanyTreeStructureDto> found = findCompanyByCurrentCompany(company.getChildren(), targetCompany);
                if (found != null) {
                    return found;
                }
            }
        }

        return null;
    }


    public ReportResponse merge(ReportByIdRequest request) {
        for (String table : request.getTables()) {
            TableConfig tableConfig = tableConfigRepository.findBytName(table);
            if (tableConfig == null) {
                continue;
            }
            List<Report> reports = new ArrayList<>();
            //根节点是合并数据，所以要跳过，每次都是重新生成
            boolean skip = true;
            for (CompanyTreeStructure companyTreeStructureDto : request.getCompanyTreeStructure()) {
                if (skip) {
                    skip = false;
                    continue;
                }
                Optional<Report> report = reportRepository.findByBsdwxydmAndReporttypeAndMergeType(companyTreeStructureDto.getCurrentCompanyUscc(), table, companyTreeStructureDto.getMergeType());
                if (report.isPresent()) {
                    reports.add(report.get());
                }
            }
            if (CollectionUtil.isEmpty(reports)) {
                continue;
            }

            List<List<List<Object>>> tableDataList = new ArrayList<>();
            List<String> reportinfos = reports.stream().map(report -> report.getReportinfo()).collect(Collectors.toList());
            for (String reportinfo : reportinfos) {
                List<List<Object>> reportInfoArray = JSONPath.read(reportinfo, "$.displayData", List.class);
                tableDataList.add(reportInfoArray);
            }
            //List<List<Object>> lists = mergeTableDataWithSkip(tableDataList, tableConfig.getFixedRows(), tableConfig.getFixedColumns());
            //查询表映射配置
            List<TableRowMapping> tableRowMappings = tableRowMappingRepository.getTableRowMappingByProjectNoAndTName(request.getAuditCompanyUscc(), table);

            List<List<Object>> lists = mergeTableDataAndRowsWithSkip(tableDataList, tableConfig.getFixedRows(), tableConfig.getFixedColumns(), tableRowMappings);

            // 创建 lists 的深拷贝，避免循环引用问题
            String listsJson = JSON.toJSONString(lists);
            List<List<Object>> listsCopy = JSON.parseObject(listsJson, new TypeReference<List<List<Object>>>() {
            });

            Report report = reports.get(0);
            JSONObject jsonObject = JSON.parseObject(report.getReportinfo());
            jsonObject.put("displayData", lists);
            jsonObject.put("data", listsCopy);

            Report report1 = new Report();
            report1.setId(null);
            report1.setReportinfo(jsonObject.toJSONString());
            report1.setBsdwxydm(request.getCompanyTreeStructure().get(0).getCurrentCompanyUscc());
            report1.setMergeType(MergeTypeEnum.SUM.getCode());
            report1.setReporttype(report.getReporttype());

            reportRepository.upsert(report1);
        }

        ReportResponse response = new ReportResponse();
        response.setStatus("success");
        return response;
    }

    /**
     * 合并报表
     *
     * @param sjxmbh
     * @param bsdwxydm
     * @param mergeNode
     * @param tables
     * @param auditCompanyUscc
     * @return
     */
    public ReportResponse mergeReportsById(String sjxmbh, String bsdwxydm, Integer mergeNode, List<String> tables, String auditCompanyUscc) {

        List<CompanyTreeStructureDto> companyUscc = companyTreeStructureService.getCompanyTree(auditCompanyUscc);
        //兼容三级往二级 合并，或者 4级别往3级别合并 || 4、3->2
        companyUscc = findCompanyByCurrentCompany(companyUscc, bsdwxydm);
        List<CompanyTreeStructureDto> operateTree = new ArrayList<>();

        if (MergeNodeEnum.getByCode(mergeNode) == MergeNodeEnum.DIRECT_SUBORDINATE) {
            // 查找当前公司节点或其子节点中currentCompanyUscc = bsdwxydm的数据
            // 找到后将当前数据放进operateTree，并将children中所有mergeType = 2的元素放进operateTree，不再向下遍历
            findAndCollectDirectSubordinates(companyUscc, bsdwxydm, operateTree, true);
        } else if (MergeNodeEnum.getByCode(mergeNode) == MergeNodeEnum.ALL_SUBORDINATE) {
            // 查找当前公司节点或其子节点中currentCompanyUscc = bsdwxydm的数据
            // 找到后将当前数据放进operateTree，并将children中所有mergeType = 2的元素放进operateTree，继续向下遍历
            findAndCollectAllSubordinates(companyUscc, bsdwxydm, operateTree);
        }

        for (String table : tables) {

            TableConfig tableConfig = tableConfigRepository.findBytName(table);
            if (tableConfig == null) {
                continue;
            }
            List<Report> reports = new ArrayList<>();
            for (CompanyTreeStructureDto companyTreeStructureDto : operateTree) {
                Optional<Report> report = reportRepository.findByBsdwxydmAndReporttypeAndMergeType(companyTreeStructureDto.getCurrentCompanyUscc(), table, MergeTypeEnum.HQ_SUM.getCode());
                if (report.isPresent()) {
                    reports.add(report.get());
                }
            }
            if (CollectionUtil.isEmpty(reports)) {
                continue;
            }

            List<List<List<Object>>> tableDataList = new ArrayList<>();
            List<String> reportinfos = reports.stream().map(report -> report.getReportinfo()).collect(Collectors.toList());
            for (String reportinfo : reportinfos) {
                List<List<Object>> reportInfoArray = JSONPath.read(reportinfo, "$.displayData", List.class);
                tableDataList.add(reportInfoArray);
            }
            List<List<Object>> lists = mergeTableDataWithSkip(tableDataList, tableConfig.getFixedRows(), tableConfig.getFixedColumns());

            // 创建 lists 的深拷贝，避免循环引用问题
            String listsJson = JSON.toJSONString(lists);
            List<List<Object>> listsCopy = JSON.parseObject(listsJson, new TypeReference<List<List<Object>>>() {
            });

            Report report = reports.get(0);
            JSONObject jsonObject = JSON.parseObject(report.getReportinfo());
            jsonObject.put("displayData", lists);
            jsonObject.put("data", listsCopy);

            Report report1 = new Report();
            report1.setId(null);
            report1.setReportinfo(jsonObject.toJSONString());
            report1.setBsdwxydm(report.getBsdwxydm());
            report1.setMergeType(MergeTypeEnum.SUM.getCode());
            report1.setReporttype(report.getReporttype());

            reportRepository.upsert(report1);
        }

        ReportResponse response = new ReportResponse();
        response.setStatus("success");
        return response;
    }


    /**
     * 合并多个表格数据，将相同行相同列的数值相加，支持跳过指定行数和列数
     *
     * @param tableDataList 多个表格数据列表
     * @param skipRows      跳过的行数（从0开始计数）
     * @param skipColumns   跳过的列数（从0开始计数）
     * @return 合并后的表格数据
     */
    public List<List<Object>> mergeTableDataWithSkip(List<List<List<Object>>> tableDataList, int skipRows, int skipColumns) {
        if (tableDataList == null || tableDataList.isEmpty()) {
            return new ArrayList<>();
        }

        // 以第一个表格为基准进行合并
        List<List<Object>> result = new ArrayList<>();

        // 获取第一个表格作为基准
        List<List<Object>> baseTable = tableDataList.get(0);

        // 复制基准表格结构到结果中
        for (List<Object> row : baseTable) {
            List<Object> newRow = new ArrayList<>();
            for (Object cell : row) {
                newRow.add(cell);
            }
            result.add(newRow);
        }

        // 遍历其余表格进行合并
        for (int tableIndex = 1; tableIndex < tableDataList.size(); tableIndex++) {
            List<List<Object>> currentTable = tableDataList.get(tableIndex);

            // 遍历每一行
            for (int rowIndex = 0; rowIndex < currentTable.size() && rowIndex < result.size(); rowIndex++) {
                // 跳过指定的行数
                if (rowIndex < skipRows) {
                    continue;
                }

                List<Object> currentRow = currentTable.get(rowIndex);
                List<Object> resultRow = result.get(rowIndex);

                // 遍历每一列
                for (int colIndex = 0; colIndex < currentRow.size() && colIndex < resultRow.size(); colIndex++) {
                    // 跳过指定的列数
                    if (colIndex < skipColumns || colIndex == currentRow.size() - 1) {
                        continue;
                    }

                    Object currentValue = currentRow.get(colIndex);
                    Object resultValue = resultRow.get(colIndex);
                    if (StringUtils.isEmpty(currentValue)) {
                        continue;
                    }
                    if (StringUtils.isEmpty(resultValue)) {
                        resultRow.set(colIndex, currentValue);
                        continue;
                    }
                    BigDecimal add = new BigDecimal(resultValue.toString()).add(new BigDecimal(currentValue.toString()));
                    resultRow.set(colIndex, add.toString());
                }
                result.set(rowIndex, resultRow);
            }
        }

        return result;
    }

    /**
     * 核心合并方法
     *
     * @param data               原始数据
     * @param mapping            映射规则（如{"张三":"银行存款"}）
     * @param groupByColumnIndex 分组依据列下标（如0代表第一列）
     * @param skipColumns        跳过的前导列数（如2）
     */
    public static List<List<Object>> mergeData(List<List<String>> data, Map<String, String> mapping, int groupByColumnIndex, int skipColumns) {
        // 1. 应用映射规则（仅修改分组依据列）
        applyMapping(data, mapping, groupByColumnIndex);

        // 2. 按指定列分组
        Map<String, List<List<String>>> groupedData = new LinkedHashMap<>();
        for (List<String> row : data) {
            String groupKey = row.get(groupByColumnIndex);
            groupedData.computeIfAbsent(groupKey, k -> new ArrayList<>()).add(row);
        }

        // 3. 合并每组数据
        return groupedData.values().stream()
                .map(group -> mergeGroup(group, groupByColumnIndex, skipColumns))
                .collect(Collectors.toList());
    }

    // 优化：仅修改分组依据列的值
    private static void applyMapping(List<List<String>> data, Map<String, String> mapping, int groupByColumnIndex) {
        if (mapping == null) return;
        for (List<String> row : data) {
            String originalValue = row.get(groupByColumnIndex);
            if (mapping.containsKey(originalValue)) {
                // 只修改分组依据列的值
                row.set(groupByColumnIndex, mapping.get(originalValue));
            }
        }
    }

    // 合并单组数据（保留原始列结构）

    /**
     * @param group
     * @param groupByColumnIndex 下标
     * @param skipColumns        下标
     * @return
     */
    private static List<Object> mergeGroup(List<List<String>> group, int groupByColumnIndex, int skipColumns) {
        int colCount = group.get(0).size();
        List<Object> mergedRow = new ArrayList<>(colCount);

        // 1. 复制分组依据列的值（不修改其他列）
        for (int i = 0; i < colCount; i++) {
            if (i == groupByColumnIndex) {
                mergedRow.add(group.get(0).get(i)); // 分组列用首行值
            } else {
                mergedRow.add(""); // 其他列先占位
            }
        }

        // 2. 处理数值列（跳过前导列和分组列）
        for (int colIdx = skipColumns; colIdx < colCount; colIdx++) {
            if (colIdx == groupByColumnIndex) continue; // 跳过分组列

            //int sum = 0;
            BigDecimal sum = BigDecimal.ZERO;
            boolean hasValue = false;
            for (List<String> row : group) {
                String val = row.get(colIdx);
                if (!val.isEmpty()) {
                    try {
                        //sum += Integer.parseInt(val);
                        BigDecimal bigDecimal = new BigDecimal(val);
                        sum = sum.add(bigDecimal);
                        hasValue = true;
                    } catch (NumberFormatException ignored) {
                        // 非数值保留首次出现的值
                        if (StringUtils.isEmpty(mergedRow.get(colIdx))) {
                            mergedRow.set(colIdx, val);
                        }
                    }
                }
            }
            if (hasValue) {
                mergedRow.set(colIdx, sum.toString());
            }
        }
        return mergedRow;
    }


    public List<List<Object>> mergeTableDataAndRowsWithSkip(List<List<List<Object>>> tableDataList, int skipRows, int skipColumns, List<TableRowMapping> tableRowMappings) {
        if (tableDataList == null || tableDataList.isEmpty()) {
            return new ArrayList<>();
        }

        Map<String, String> rowNameMapping = new HashMap<>();
        //是否有字段映射
        if (CollectionUtil.isNotEmpty(tableRowMappings)) {
            for (TableRowMapping tableRowMapping : tableRowMappings) {
                if (org.apache.commons.lang3.StringUtils.isAnyBlank(tableRowMapping.getMapping(), tableRowMapping.getRowName())) {
                    continue;
                }
                String[] names = tableRowMapping.getMapping().split(",");
                for (String name : names) {
                    rowNameMapping.put(name, tableRowMapping.getRowName());
                }
            }
            boolean flag = false;
            List<List<String>> dataTables = new ArrayList<>();
            for (List<List<Object>> lists : tableDataList) {
                if (flag) {
                    //多个表合并，跳过表头
                    for (int i = 0; i < skipRows; i++) {
                        lists.remove(0);
                    }
                }
                //+排序
                List<String> endElement = null;
                if (dataTables.size() - 1 > 0) {
                    endElement = new ArrayList<>(dataTables.get(dataTables.size() - 1));
                    dataTables.remove(dataTables.size() - 1);
                }
                for (List<Object> list : lists) {
                    List<String> collect = list.stream()
                            .map(obj -> obj == null ? null : obj.toString())
                            .collect(Collectors.toList());
                    dataTables.add(collect);
                }
                //-增加尾行
                if (endElement != null) {
                    dataTables.add(endElement);
                }

                flag = true;
            }

            return mergeData(dataTables, rowNameMapping, tableRowMappings.get(0).getColumnIndex(), skipColumns);
        }


        // 以第一个表格为基准进行合并
        List<List<Object>> result = new ArrayList<>();

        // 获取第一个表格作为基准
        List<List<Object>> baseTable = tableDataList.get(0);

        // 复制基准表格结构到结果中
        for (List<Object> row : baseTable) {
            List<Object> newRow = new ArrayList<>();
            for (Object cell : row) {
                newRow.add(cell);
            }
            result.add(newRow);
        }

        // 遍历其余表格进行合并
        for (int tableIndex = 1; tableIndex < tableDataList.size(); tableIndex++) {
            List<List<Object>> currentTable = tableDataList.get(tableIndex);

            // 遍历每一行
            for (int rowIndex = 0; rowIndex < currentTable.size() && rowIndex < result.size(); rowIndex++) {
                // 跳过指定的行数
                if (rowIndex < skipRows) {
                    continue;
                }

                List<Object> currentRow = currentTable.get(rowIndex);
                List<Object> resultRow = result.get(rowIndex);

                // 遍历每一列
                for (int colIndex = 0; colIndex < currentRow.size() && colIndex < resultRow.size(); colIndex++) {
                    // 跳过指定的列数
                    if (colIndex < skipColumns || colIndex == currentRow.size() - 1) {
                        continue;
                    }

                    Object currentValue = currentRow.get(colIndex);
                    Object resultValue = resultRow.get(colIndex);
                    if (StringUtils.isEmpty(currentValue)) {
                        continue;
                    }
                    if (StringUtils.isEmpty(resultValue)) {
                        resultRow.set(colIndex, currentValue);
                        continue;
                    }
                    BigDecimal add = new BigDecimal(resultValue.toString()).add(new BigDecimal(currentValue.toString()));
                    resultRow.set(colIndex, add.toString());
                }
                result.set(rowIndex, resultRow);
            }
        }

        return result;
    }


    /**
     * 处理DIRECT_SUBORDINATE情况：
     * 查找currentCompanyUscc = bsdwxydm的节点，将其及直接子节点中mergeType=2的节点加入结果集
     */
    private void findAndCollectDirectSubordinates(List<CompanyTreeStructureDto> companyList, String bsdwxydm, List<CompanyTreeStructureDto> operateTree, boolean isDirect) {
        if (companyList == null || companyList.isEmpty()) {
            return;
        }

        for (CompanyTreeStructureDto company : companyList) {
            // 如果找到匹配的节点
            if (bsdwxydm.equals(company.getCurrentCompanyUscc())) {
                // 将当前节点加入结果集
                //operateTree.add(company);

                // 将直接子节点中mergeType=2的节点加入结果集（不再向下遍历）
                if (company.getChildren() != null) {
                    for (CompanyTreeStructureDto child : company.getChildren()) {

                        if (child.getMergeType() != null && child.getMergeType() == 2) {
                            operateTree.add(child);
                        }
                        //直接下级
                        else if (isDirect && !child.getCurrentCompanyUscc().equals(company.getCurrentCompanyUscc()) && child.getMergeType() == MergeTypeEnum.SUM.getCode()) {
                            CompanyTreeStructureDto companyTreeStructureDto = new CompanyTreeStructureDto();
                            BeanUtils.copyProperties(child, companyTreeStructureDto);
                            companyTreeStructureDto.setMergeType(MergeTypeEnum.HQ_SUM.getCode());
                            operateTree.add(companyTreeStructureDto);
                        }
                    }
                }
                return; // 找到后直接返回
            }

            // 递归查找子节点
            findAndCollectDirectSubordinates(company.getChildren(), bsdwxydm, operateTree, false);
        }
    }

    /**
     * 处理ALL_SUBORDINATE情况：
     * 查找currentCompanyUscc = bsdwxydm的节点，将其及所有子节点中mergeType=2的节点加入结果集
     */
    private void findAndCollectAllSubordinates(List<CompanyTreeStructureDto> companyList, String bsdwxydm, List<CompanyTreeStructureDto> operateTree) {
        if (companyList == null || companyList.isEmpty()) {
            return;
        }

        for (CompanyTreeStructureDto company : companyList) {
            // 如果找到匹配的节点
            if (bsdwxydm.equals(company.getCurrentCompanyUscc())) {
                // 将当前节点加入结果集
                //operateTree.add(company);

                // 将所有子节点中mergeType=2的节点加入结果集（继续向下遍历）
                collectAllChildrenWithMergeType(company.getChildren(), operateTree);
                return; // 找到后直接返回
            }

            // 递归查找子节点
            findAndCollectAllSubordinates(company.getChildren(), bsdwxydm, operateTree);
        }
    }

    /**
     * 遍历所有子节点（包括子孙节点），收集所有mergeType=2的节点
     */
    private void collectAllChildrenWithMergeType(List<CompanyTreeStructureDto> children, List<CompanyTreeStructureDto> operateTree) {
        if (children == null || children.isEmpty()) {
            return;
        }

        for (CompanyTreeStructureDto child : children) {
            // 如果当前子节点的mergeType=2，则加入结果集
            if (child.getMergeType() != null && child.getMergeType() == 2) {
                operateTree.add(child);
            }

            // 继续向下遍历处理孙子节点
            collectAllChildrenWithMergeType(child.getChildren(), operateTree);
        }
    }


    /**
     * 遍历子节点集合，收集所有mergeType=2的节点
     */
    private void collectChildrenWithMergeType(List<CompanyTreeStructureDto> children, List<CompanyTreeStructureDto> operateTree) {
        if (children == null || children.isEmpty()) {
            return;
        }

        for (CompanyTreeStructureDto child : children) {
            // 如果当前子节点的mergeType=2，则加入结果集
            if (child.getMergeType() != null && child.getMergeType() == 2) {
                operateTree.add(child);
            }

            // 递归处理孙子节点
            collectChildrenWithMergeType(child.getChildren(), operateTree);
        }
    }


    private ReportResponse mergeReports(ReportRequest request) {
        ReportResponse response = new ReportResponse();
        response.setProjectId(request.getProjectId());

        try {
            List<Map<String, Object>> mergedData = new ArrayList<>();

            for (Map.Entry<String, List<Map<String, Object>>> entry : request.getReportStructures().entrySet()) {
                String key = entry.getKey();
                List<Map<String, Object>> v = entry.getValue();
                mergedData = mergeStructures(v, mergedData);
            }

            response.setMergedReport(mergedData);
            response.setStatus("SUCCESS");
            response.setMessage("Reports merged successfully");

        } catch (Exception e) {
            response.setStatus("ERROR");
            response.setMessage("Failed to merge reports: " + e.getMessage());
        }

        return response;
    }

    // 合并多个结构的函数
    @SafeVarargs
    private static List<Map<String, Object>> mergeStructures(List<Map<String, Object>>... structures) {
        List<Map<String, Object>> mergedList = new ArrayList<>();
        if (structures[1].isEmpty()) {
            return structures[0];
        }
        // 假设所有的结构长度一致，可以遍历任意结构的第一个元素进行合并
        for (int i = 0; i < structures[0].size(); i++) {
            Map<String, Object> mergedItem = new HashMap<>(structures[0].get(i)); // 初始化为第一个结构的项

            // 遍历其他结构并合并
            for (int j = 1; j < structures.length; j++) {
                Map<String, Object> currentItem = structures[j].get(i); // 获取当前结构的第 i 项
                mergedItem = mergeMaps(mergedItem, currentItem); // 合并当前项
            }
            mergedList.add(mergedItem);
        }
        return mergedList;
    }

    // 合并两个Map
    private static Map<String, Object> mergeMaps(Map<String, Object> map1, Map<String, Object> map2) {
        Map<String, Object> mergedMap = new HashMap<>();

        for (String key : map1.keySet()) {
            if (map2.containsKey(key)) {
                Object value1 = map1.get(key);
                Object value2 = map2.get(key);

                // 如果值是Map类型，递归合并
                if (value1 instanceof Map && value2 instanceof Map) {
                    mergedMap.put(key, mergeMaps((Map<String, Object>) value1, (Map<String, Object>) value2));
                }
                // 如果值是List类型，合并每个元素
                else if (value1 instanceof List && value2 instanceof List) {
                    mergedMap.put(key, mergeLists((List<Map<String, Object>>) value1, (List<Map<String, Object>>) value2));
                }
                // 如果是其他类型，进行累加
                else if (value1 instanceof Number && value2 instanceof Number) {
                    mergedMap.put(key, ((Number) value1).doubleValue() + ((Number) value2).doubleValue());
                } else {
                    mergedMap.put(key, value1);
                }
            }
        }

        return mergedMap;
    }

    // 合并List
    private static List<Map<String, Object>> mergeLists(List<Map<String, Object>> list1, List<Map<String, Object>> list2) {
        List<Map<String, Object>> mergedList = new ArrayList<>();
        for (int i = 0; i < list1.size(); i++) {
            mergedList.add(mergeMaps(list1.get(i), list2.get(i)));
        }
        return mergedList;
    }

    public Response getReport(ReportByIdRequest request) {
        Response response = new Response();
        Report report = reportRepository.getReport(request.getTname(), request.getBsdwxydms(), request.getMergeType());
        if (report == null) {
            ReportTemplate reportTemplate = reportTemplateRepository.getReportTemplateByReporttype(request.getTname());
            if (reportTemplate != null) {
                report = new Report();
                report.setReporttype(request.getTname());
                report.setReportinfo(reportTemplate.getReportinfo());
                report.setBsdwxydm(request.getBsdwxydms());
                report.setMergeType(request.getMergeType());
            }
        }
        response.setStatus("success");
        response.setData(report);
        return response;
    }

    public static void main(String[] args) {

        List<List<Integer>> list = new ArrayList<>();

        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list.add(list1);
        list.add(list1);
        list.add(list1);

        for (List<Integer> integers : list) {
            integers.add(4);
        }

        for (List<Integer> integers : list) {
            integers.add(4);
        }


    }

    public Response save(Report report) {

        ReportTemplate reportTemplate = reportTemplateRepository.getReportTemplateByReporttype(report.getReporttype());
        if (reportTemplate == null) {
            Response response = new Response();
            response.setStatus("fail");
            response.setMessage("未查到模板");
            return response;
        }
        JSONObject reportInfo = JSONObject.parseObject(reportTemplate.getReportinfo());
        JSONPath.set(reportInfo, "$.data", JSON.parseArray(report.getReportinfo()));
        report.setReportinfo(reportInfo.toJSONString());
        reportRepository.upsert(report);
        Response response = new Response();
        response.setStatus("success");
        response.setMessage("success");
        return response;
    }
}
